import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { 
  getBookList, 
  getBookById, 
  createBook, 
  updateBook, 
  deleteBook,
  batchDeleteBooks,
  updateBookStatus 
} from '@/api/book'

// ==================== 异步操作 ====================

/**
 * 获取图书列表
 */
export const fetchBookList = createAsyncThunk(
  'book/fetchList',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getBookList(params)
      // 将请求参数一起返回，用于更新分页状态
      return { ...response, requestParams: params }
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 获取图书详情
 */
export const fetchBookDetail = createAsyncThunk(
  'book/fetchDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getBookById(id)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '获取图书详情失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 新增图书
 */
export const addBook = createAsyncThunk(
  'book/add',
  async (data, { rejectWithValue }) => {
    try {
      const response = await createBook(data)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '新增图书失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 更新图书
 */
export const editBook = createAsyncThunk(
  'book/edit',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateBook(id, data)
      if (response.code === 200) {
        return response.data
      }
      return rejectWithValue(response.message || '更新图书失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 删除图书
 */
export const removeBook = createAsyncThunk(
  'book/remove',
  async (id, { rejectWithValue }) => {
    try {
      const response = await deleteBook(id)
      if (response.code === 200) {
        return id
      }
      return rejectWithValue(response.message || '删除图书失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 批量删除图书
 */
export const removeBatchBooks = createAsyncThunk(
  'book/removeBatch',
  async (ids, { rejectWithValue }) => {
    try {
      const response = await batchDeleteBooks(ids)
      if (response.code === 200) {
        return ids
      }
      return rejectWithValue(response.message || '批量删除失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

/**
 * 更新图书状态
 */
export const changeBookStatus = createAsyncThunk(
  'book/changeStatus',
  async ({ id, status }, { rejectWithValue }) => {
    try {
      const response = await updateBookStatus(id, status)
      if (response.code === 200) {
        return { id, status }
      }
      return rejectWithValue(response.message || '更新状态失败')
    } catch (error) {
      return rejectWithValue(error.message || '网络请求失败')
    }
  }
)

// ==================== Slice ====================

const bookSlice = createSlice({
  name: 'book',
  initialState: {
    // 图书列表
    bookList: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    
    // 当前图书详情
    currentBook: null,
    
    // 加载状态
    loading: false,
    detailLoading: false,
    
    // 错误信息
    error: null
  },
  reducers: {
    // 清空错误
    clearError: (state) => {
      state.error = null
    },
    // 重置当前图书
    resetCurrentBook: (state) => {
      state.currentBook = null
    },
    // 设置分页参数
    setPageParams: (state, action) => {
      state.currentPage = action.payload.page || state.currentPage
      state.pageSize = action.payload.size || state.pageSize
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取图书列表
      .addCase(fetchBookList.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchBookList.fulfilled, (state, action) => {
        state.loading = false
        state.bookList = action.payload.data || []
        state.total = action.payload.total || 0
        // 使用请求参数更新分页状态（因为后端不返回分页字段）
        const params = action.payload.requestParams || {}
        if (params.page !== undefined) {
          state.currentPage = params.page
        }
        if (params.size !== undefined) {
          state.pageSize = params.size
        }
      })
      .addCase(fetchBookList.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '获取图书列表失败'
      })
      
      // 获取图书详情
      .addCase(fetchBookDetail.pending, (state) => {
        state.detailLoading = true
        state.error = null
      })
      .addCase(fetchBookDetail.fulfilled, (state, action) => {
        state.detailLoading = false
        state.currentBook = action.payload
      })
      .addCase(fetchBookDetail.rejected, (state, action) => {
        state.detailLoading = false
        state.error = action.payload || '获取图书详情失败'
      })
      
      // 新增图书
      .addCase(addBook.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addBook.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addBook.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '新增图书失败'
      })
      
      // 更新图书
      .addCase(editBook.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editBook.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editBook.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '更新图书失败'
      })
      
      // 删除图书
      .addCase(removeBook.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeBook.fulfilled, (state, action) => {
        state.loading = false
        state.bookList = state.bookList.filter(book => book.id !== action.payload)
        state.total -= 1
      })
      .addCase(removeBook.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '删除图书失败'
      })
      
      // 批量删除
      .addCase(removeBatchBooks.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeBatchBooks.fulfilled, (state, action) => {
        state.loading = false
        state.bookList = state.bookList.filter(book => !action.payload.includes(book.id))
        state.total -= action.payload.length
      })
      .addCase(removeBatchBooks.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '批量删除失败'
      })
      
      // 更新状态
      .addCase(changeBookStatus.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(changeBookStatus.fulfilled, (state, action) => {
        state.loading = false
        const book = state.bookList.find(b => b.id === action.payload.id)
        if (book) {
          book.status = action.payload.status
        }
      })
      .addCase(changeBookStatus.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload || '更新状态失败'
      })
  }
})

export const { clearError, resetCurrentBook, setPageParams } = bookSlice.actions

export default bookSlice.reducer

